# Copyright (C) 2005-2006 Frederic Back <fredericback@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.

import string
import sys, csv
from cStringIO import StringIO
from operator import itemgetter
from codecs import *

from mezoGISlib._plugins import Argument, UserPlugin
from mezoGISlib import getGeometryExtent, Table

def register():
    return ImportSql()

class ImportSql(UserPlugin):

    def __init__(self):
        UserPlugin.__init__(self, "Run SQL From File", "Execute an SQL script", "Execute an SQL script")
        self.arguments = {
            "input file": Argument(Argument.tfileopen,"the path of the SQL script","script.sql"),
        }

    def getInput(self):
        return self.arguments

    def launch(self, database):
        f = open( self.arguments["input file"].value , 'r')
        lines = f.readlines()
        count = 0.0
        total = float(len(lines))
        buf = ""
        cursor = database.handle.cursor()
        for line in lines:
            self.progress( count/total*100 )

            # skip commented lines
            if len(line) >= 2:
                if line[:2] == "--":
                    continue

            p = line.find(";")
            if p != -1: # if line contains a semi-colon
                buf += line[:p]
                print "execute------------------------------"
                print buf.strip()
                try:
                    cursor.execute(str(buf))
                except Exception, e:
                    raise Exception, e
                    f.close()
                    return
                buf = line[p+1:]
            else:
                buf += line
            

        f.close()
        database.handle.commit()
        self.progress(100)
        cursor.close()
